package com.spring.demo3.eg1;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib代理(类和接口)
 *
 * @author vhans
 */
public class CostTimeProxy implements MethodInterceptor {

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long startTime = System.nanoTime();
        Object result = methodProxy.invokeSuper(o, objects);
        long endTime = System.nanoTime();
        System.out.println("方法" + method.getName() + "耗时(纳秒):" + (endTime - startTime));
        return result;
    }

    public static Object createProxy(Object target, Class<?>[] classes) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setInterfaces(classes);
        enhancer.setCallback(new CostTimeProxy());
        return enhancer.create();
    }
}
